package com.hugehard.here;

import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hugehard.here.ContactsManager.BaseContactItem;
import com.hugehard.here.ContactsManager.CallLogItem;

public class RecentContactView {

	private final static String TAG = RecentContactView.class.getSimpleName();
	
	private Context mContext = null;
	private View mView = null;
	private LayoutInflater mInflater = null;
	private ContactAdapter mAdapter = null;
	
	private int mHalfScreenWidth = 240;
	private ArrayList<Integer> mColorList = new ArrayList<Integer>();
	
	public RecentContactView(Context context) {
		mContext = context;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		ListView listView = new ListView(context);
		mView = listView;
		
		Resources resources = context.getResources();		
        mColorList.add(resources.getColor(R.color.light_blue_1));
        mColorList.add(resources.getColor(R.color.light_cornflower_blue_1));
        mColorList.add(resources.getColor(R.color.light_cyan_1));
        mColorList.add(resources.getColor(R.color.light_green_1));
        mColorList.add(resources.getColor(R.color.light_magenta_1));
        mColorList.add(resources.getColor(R.color.light_orange_1));
        mColorList.add(resources.getColor(R.color.light_purple_1));
        mColorList.add(resources.getColor(R.color.light_red_1));
        mColorList.add(resources.getColor(R.color.light_yellow_1));
        
        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int width = displaymetrics.widthPixels;
        mHalfScreenWidth = width / 2;
        
        mAdapter = new ContactAdapter();
        listView.setAdapter(mAdapter);
        
        mAdapter.setItems(ContactsManager.getInstance().getRecentContactItemList());
        mAdapter.notifyDataSetChanged();
        
        listView.setOnItemClickListener(mOnItemClickListener);
	}
	
	private boolean selectContactItem(final BaseContactItem item) {
		if (item == null) {
			return false;
		}
		LayoutInflater inflater = (LayoutInflater)
		        mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View dialogView = inflater.inflate(R.layout.hh_dialog,
		        null);

		TextView text = (TextView) dialogView.findViewById(R.id.hh_dialog_textview);
		String contentStr = mContext.getResources().getString(R.string.hh_dialog_content);
		
		text.setText(contentStr + " " + item.mContactName);
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setView(dialogView);
		final AlertDialog alertDialog = builder.create();

		View cancelBtn = dialogView.findViewById(R.id.btn_cancel);
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialog.cancel();
			}
		});

		View okBtn = dialogView.findViewById(R.id.btn_ok);
		okBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LocationManager locationManager = (LocationManager) mContext
						.getSystemService(Context.LOCATION_SERVICE);
				Criteria crit = new Criteria();
				crit.setAccuracy(Criteria.ACCURACY_FINE);
				String provider = locationManager.getBestProvider(crit, true);
				Location location = locationManager
						.getLastKnownLocation(provider);
				double latitude = location.getLatitude();
				double longtiude = location.getLongitude();
				String smsText = String.format(Locale.getDefault(),
						"I'm here! (%f, %f)", latitude, longtiude);

				try {
					SmsManager smsManager = SmsManager.getDefault();
					smsManager.sendTextMessage(item.mPhoneNumber, null,
							smsText, null, null);
					Toast.makeText(mContext, "SMS Sent!", Toast.LENGTH_LONG)
							.show();
				} catch (Exception e) {
					Toast.makeText(mContext,
							"SMS faild, please try again later!",
							Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
				alertDialog.cancel();
			}
		});
		alertDialog.show();
		return true;
	}
	
	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			BaseContactItem item = mAdapter.getItem(arg2);
			selectContactItem(item);
		}
	};
	
	public View getView() {
		return mView;
	}
    
    private class ContactAdapter extends BaseAdapter {    	
    	private ArrayList<CallLogItem> mItems = new ArrayList<CallLogItem>();
		private ArrayList<Integer> mColorIndexList = new ArrayList<Integer>() {
			private static final long serialVersionUID = -8470453553472840983L;
			{
				add(0);
				add(1);
				add(2);
				add(3);
			}
		};
    	
    	class ViewHolder {
    		public TextView mContactTextView1 = null;
    		public TextView mContactTextView2 = null;
    		public ImageView mPhoneTypeImageView = null;
    		
    		public View mContactLayout1 = null;
    		public View mContactLayout2 = null;
    	}
    	
    	public void setItems(final ArrayList<CallLogItem> items) {
    		mItems = items;
    	}
    	
    	public void clear() {
    		mItems.clear();
    	}
    	
		@Override
		public int getCount() {
			if (mItems.size() > 4) {
				return mItems.size() - 2;
			} else {
				float temp = mItems.size() / 2;
				return (int) (temp + 1);
			}
		}

		@Override
		public CallLogItem getItem(int position) {
			CallLogItem retItem = null;
			int index = position >= 2 ? position + 2 : position;
			if (index >= 0 && index < mItems.size()) {
				retItem = mItems.get(index);
			}
			return retItem;
		}
		
		private ArrayList<CallLogItem> getHeaderItem(int position) {
			ArrayList<CallLogItem> retItems = new ArrayList<CallLogItem>();
			int index1 = position * 2;
			int index2 = index1 + 1;
			if (index1 >= 0 && index1 < mItems.size()) {
				retItems.add(mItems.get(index1));
			}
			if (index2 >= 0 && index2 < mItems.size()) {
				retItems.add(mItems.get(index2));
			}
			return retItems;
		}
		
		
		@Override
		public int getViewTypeCount() {
		    return 2;
		}

		@Override
		public int getItemViewType(int position) {
			int type = position < 2 ? 0 : 1; 
		    return type;
		}
		

		@Override
		public long getItemId(int position) {
			return 0;
		}
		
		private int getRandomColor(int colorIndex) {
			int retColor = mContext.getResources().getColor(R.color.light_blue_1);
			if (colorIndex >= 0 && colorIndex < mColorIndexList.size()) {
				Random random = new Random();
				int randomIndex = 0;
				do {
					randomIndex = random.nextInt(mColorList.size());
				} while (mColorIndexList.contains(randomIndex));
				mColorIndexList.set(colorIndex, randomIndex);
				retColor = mColorList.get(randomIndex);
			}
			return retColor;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			int type = getItemViewType(position);
			if (type == 0) {
				if (convertView == null) {
					convertView = mInflater.inflate(R.layout.contact_listiview_header, parent, false);
					convertView.setMinimumHeight(mHalfScreenWidth);
					viewHolder = new ViewHolder();
					viewHolder.mContactLayout1 = convertView.findViewById(R.id.contactLayout1);
					viewHolder.mContactLayout2 = convertView.findViewById(R.id.contactLayout2);
					viewHolder.mContactTextView1 = (TextView) convertView.findViewById(R.id.contact_name_textview);
					viewHolder.mContactTextView2 = (TextView) convertView.findViewById(R.id.contact_name_textview2);
					convertView.setTag(viewHolder);
				} else {
					viewHolder = (ViewHolder) convertView.getTag();
				}
				
				if (viewHolder != null) {
					ArrayList<CallLogItem> items = getHeaderItem(position);
					if (items != null) {
						int index = position * 2;
						if (items.size() > 0) {
							final CallLogItem item = items.get(0);
							if (item != null) {
								viewHolder.mContactTextView1.setText(item.mContactName);
								viewHolder.mContactLayout1.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										selectContactItem(item);
									}
								});
							}
						}
						if (items.size() > 1) {
							final CallLogItem item = items.get(1);
							if (item != null) {
								viewHolder.mContactTextView2.setText(item.mContactName);
								viewHolder.mContactLayout2.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										selectContactItem(item);
									}
								});
							}
						}
						viewHolder.mContactLayout1.setBackgroundColor(getRandomColor(index));
						viewHolder.mContactLayout2.setBackgroundColor(getRandomColor(index + 1));
					}
				}
			} else {
				if (convertView == null) {
					convertView = mInflater.inflate(R.layout.contact_item,
							parent, false);
					viewHolder = new ViewHolder();
					viewHolder.mContactTextView1 = (TextView) convertView
							.findViewById(R.id.contact_name_textview);
					viewHolder.mPhoneTypeImageView = (ImageView) convertView.findViewById(R.id.contact_phone_type_imageview);
					convertView.setTag(viewHolder);
				} else {
					viewHolder = (ViewHolder) convertView.getTag();
				}
				
				if (viewHolder != null) {
					CallLogItem item = getItem(position);
					if (item != null) {
						viewHolder.mContactTextView1.setText(item.mContactName);
						
						if (viewHolder.mPhoneTypeImageView == null) {
							viewHolder.mPhoneTypeImageView = (ImageView) convertView.findViewById(R.id.contact_phone_type_imageview);
							convertView.setTag(viewHolder);
						}
						
						if (item.mType == ContactsContract.CommonDataKinds.Phone.TYPE_HOME) {
							viewHolder.mPhoneTypeImageView.setImageResource(R.drawable.phone_type_home);
							viewHolder.mPhoneTypeImageView.setVisibility(View.VISIBLE);
						} else if (item.mType == ContactsContract.CommonDataKinds.Phone.TYPE_WORK) {
							viewHolder.mPhoneTypeImageView.setImageResource(R.drawable.phone_type_work);
							viewHolder.mPhoneTypeImageView.setVisibility(View.VISIBLE);
						} else {
							viewHolder.mPhoneTypeImageView.setVisibility(View.GONE);
						}
					}
				}	
			}
			return convertView;
		}
    }
}
